﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

namespace BulkSMSapplication
{
    public partial class AddPerson : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Opening SQL connection
            String connectionString = BulkSMSapplication.Properties.Settings.Default.ConnectionString;
            SqlConnection conn = new SqlConnection(connectionString);
            conn.Open();
            try
            {
                //checking if the Email (username) is available
                String checkEmail = "SELECT COUNT(*) from [Person] WHERE PhoneNumber = '" + TextBoxPhoneNumber.Text + "';";
                SqlCommand cmd = new SqlCommand(checkEmail, conn);
                int temp = int.Parse(cmd.ExecuteScalar().ToString());
                
                if (temp >= 1)
                {
                    Response.Write("<script language='javascript'>alert('A person with phone number: " + TextBoxPhoneNumber.Text + ", already exists!');</script>");
                }
                else
                {
                    //Inserting values
                    String firstName = TextBoxFirstName.Text;
                    String lastName = TextBoxLastName.Text;
                    String email = TextBoxEmail.Text;
                    String phoneNumber = TextBoxPhoneNumber.Text;
                    String address = TextBoxAddress.Text;
                    String insertQuery = "insert into [Person] (First_name, Last_name, Email, PhoneNumber, Address) values (@firstName, @lastName, @email, @phoneNumber, @address);";


                    SqlCommand command = new SqlCommand(insertQuery, conn);

                    command.Parameters.AddWithValue("@firstName", firstName);
                    command.Parameters.AddWithValue("@lastName", lastName);
                    command.Parameters.AddWithValue("@email", email);
                    command.Parameters.AddWithValue("@phoneNumber", phoneNumber);
                    command.Parameters.AddWithValue("@address", address);

                    command.ExecuteNonQuery();
                    Response.Redirect("AddPerson.aspx");
                    Response.Write("<script language='javascript'>alert('Person successfully added!');</script>");
                    
                }
            }
            catch(Exception ex)
            {
                Response.Write("<script language='javascript'>alert('Error: " + ex.ToString() + "'</script>");
            }
            conn.Close();
        }
    }
}